package cn.wit.summit.chwan.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.MessageDialog;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;

/**
 * Created by pengsk on 2018/4/19.
 */

public class DownlodingGamesFragment extends Fragment {

    RecyclerView recvcleView;
    SmartRefreshLayout refreshLayout;
    FrameLayout root_content_null_ll;
    TextView retryText;
    List<GameListBaseBean> games = new ArrayList<>();
    LayoutInflater inflater;
    Activity context;
    int from;
    @Bind(R.id.retryImg)
    ImageView retryImg;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recyclerview_layout, container, false);
        ButterKnife.bind(this, view);
        recvcleView = view.findViewById(R.id.recyclerView);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        root_content_null_ll = view.findViewById(R.id.root_content_null_ll);
        retryText = view.findViewById(R.id.retryText);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);
        context = getActivity();
        from = getArguments().getInt("from");
        if (from == 1)
            getAllDownloadingGame();
        else getAllDownloadedGame();

        if (games.size() == 0) {
            root_content_null_ll.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
            retryImg.setImageResource(R.mipmap.ic_not_data);
            retryText.setText(getActivity().getResources().getString(R.string.makemoney_ranking_nodata));
        } else {
            root_content_null_ll.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.VISIBLE);
        }
        EventBus.getDefault().register(this);
        initView();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    public static DownlodingGamesFragment newInstance(int from) {
        Bundle args = new Bundle();
        args.putSerializable("from", from);
        DownlodingGamesFragment fragment = new DownlodingGamesFragment();
        fragment.setArguments(args);
        return fragment;
    }

    MYUpdateAdapter adapter = null;

    private void initView() {
        inflater = LayoutInflater.from(context);
        recvcleView.setLayoutManager(new LinearLayoutManager(context));
        adapter = new MYUpdateAdapter();
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(context, R.drawable.item_driver_h));
        recvcleView.addItemDecoration(divider);
        recvcleView.setAdapter(adapter);
    }

    private void getAllDownloadingGame() {
        List<DownLoadTaskTable> taskTables = DownloadTaskManager.getInstance().findAllDownlodingGameByTime();
        for (DownLoadTaskTable table : taskTables) {
            games.add(table.getGameListData());
        }

    }

    private void getAllDownloadedGame() {

        List<DownLoadTaskTable> taskTables = DownloadTaskManager.getInstance().findAllDownlodedGamedownByTime();
        for (DownLoadTaskTable table : taskTables) {
            games.add(table.getGameListData());
        }
    }


    class MyupdateViewHolder extends RecyclerView.ViewHolder {

        ItemListView itemlistView;

        public MyupdateViewHolder(View itemView) {
            super(itemView);
            itemlistView = itemView.findViewById(R.id.itemView);
        }
    }

    class MYUpdateAdapter extends RecyclerView.Adapter {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View view = inflater.inflate(R.layout.gamelist_item_magin_layout, parent, false);
            MyupdateViewHolder holder = new MyupdateViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
            final MyupdateViewHolder h = (MyupdateViewHolder) holder;
            h.itemlistView.setData(context, games.get(position));
            h.itemlistView.hitLine();
            if (from == 1) {
                DownLoadTaskTable table = games.get(position).getTaskTable();
                if (table != null && (table.getDownStatus() == DownLoadStatusConfig.DOWNLOADING
                        || table.getDownStatus() == DownLoadStatusConfig.START)) {
                    if (StringUtils.isEmpty(table.getDownspeed())) {
                        h.itemlistView.hitSpeedTx();
                    } else {
                        if (games.get(position).getRefreshTime() == 0
                                || System.currentTimeMillis() - games.get(position).getRefreshTime() >= 1500) {
                            games.get(position).setRefreshTime(System.currentTimeMillis());
                            h.itemlistView.showSpeedTx(table.getDownspeed() + "/s");
                        }
                    }
                } else {
                    h.itemlistView.hitSpeedTx();
                }
            }
            h.itemlistView.setOnclickLinstener(new ItemListView.ItemDownloadInterface() {
                @Override
                public void onAdapterItemLongChildClick(View view, DownLoadTaskTable taskTable) {
                    final MessageDialog messageDialog = new MessageDialog(context);
                    messageDialog.show();
                    messageDialog.setTitle(getResources().getString(R.string.comment_dialog_title_str));
                    messageDialog.setMsg("确定需要删除吗?");
                    messageDialog.setCancelBtn(getResources().getString(R.string.comment_dialog_cancle_str), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            messageDialog.dismiss();
                        }
                    });
                    messageDialog.setOkBtn(getResources().getString(R.string.comment_dialog_ok_str), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            messageDialog.dismiss();
                            String gameId = h.itemlistView.getDataGameId();
                            int p = 0;
                            for (int i = 0; i < games.size(); i++) {
                                if (gameId.equals(games.get(i).getGame_id())) {
                                    p = i;
                                    break;
                                }
                            }

                            if (from == 1) {
                                games.remove(p);
                                notifyItemRemoved(p);
                                DownloadTool.deletTask(DownloadTaskManager.getInstance().findByGameId(gameId));
                                StatFactory.getInstance().sendGameDownload(context, gameId, 5 + "", false);
                                if (games.size()==0) {
                                    root_content_null_ll.setVisibility(View.VISIBLE);
                                    refreshLayout.setVisibility(View.GONE);
                                    retryImg.setImageResource(R.mipmap.ic_not_data);
                                    retryText.setText(getActivity().getResources().getString(R.string.makemoney_ranking_nodata));
                                }
                            } else {
                                APKUtils.getInstance(context).uninstallApk(context, games.get(p).getGame_package_name());
                                adapter.notifyDataSetChanged();
                            }
                        }
                    });
                }


            });

        }

        @Override
        public int getItemCount() {
            return games.size();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        for (int i = 0; i < games.size(); i++) {
            GameListBaseBean bean = games.get(i);

            if (bean.getGame_id().equals(downloadEvent.getGameId())) {
                DownLoadTaskTable table = bean.getTaskTable();
                if (table == null) {
                    table = bean.getDownloadTaskTableSimple();
                }
                table.setDownStatus(downloadEvent.status);
                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING
                        || downloadEvent.getStatus() == DownLoadStatusConfig.START) {
                    table.setDownprogress(downloadEvent.getProgress());
                    table.setDownspeed(downloadEvent.getSpeed());
                } else {
                    table.setDownspeed("");
                }
                View view = recvcleView.getLayoutManager().findViewByPosition(i);
                ItemListView itemView = view.findViewById(R.id.itemView);
                DownloadViewStroke dowView = itemView.getDownView();
                dowView.updateButn(table);
                if (from == 1) {
                    if (StringUtils.isEmpty(table.getDownspeed())) {
                        if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING
                                || downloadEvent.getStatus() == DownLoadStatusConfig.START) {
                            itemView.showSpeedTx("0KB/s");
                        } else {
                            itemView.hitSpeedTx();
                        }
                    } else {
                        if (games.get(i).getRefreshTime() == 0
                                || System.currentTimeMillis() - games.get(i).getRefreshTime() >= 1500) {
                            games.get(i).setRefreshTime(System.currentTimeMillis());
                            itemView.showSpeedTx(table.getDownspeed() + "/s");
                        }
                    }
                }
            }

        }

        if (from == 1 && downloadEvent.getStatus() == DownLoadStatusConfig.INSTALLED) {
            games.clear();
            getAllDownloadingGame();
            adapter.notifyDataSetChanged();
        }


        if (from == 2 && downloadEvent.getStatus() == DownLoadStatusConfig.INSTALLED) {
            games.clear();
            getAllDownloadedGame();
            adapter.notifyDataSetChanged();
        }
        if (from == 2 && downloadEvent.getStatus() == DownLoadStatusConfig.DELETED) {
            games.clear();
            getAllDownloadedGame();
            adapter.notifyDataSetChanged();
        }

    }
}
